const jwt = require("jsonwebtoken")
const db = require("./db")
db.init()
module.exports = async (req, res, next) => {

    if (req.method == "POST" && req.path == '/login') {
        const { username, password } = req.body
        console.log(username, password)

        const isPass = await db.checkUser(username, password)
        if (isPass) {
            let token = jwt.sign({ username }, "2302B")
            console.log(token)
            return res.status(200).json({
                success: true,
                data: { token },
            })
        } else {

            return res.status(200).json({
                success: false,
                data: {
                }
            })
        }
    }
    if (req.method == "POST" && req.path == 'register') {
        const { username, password } = req.body
        const registerInfo = await db.register(username, password)
        return res.status(200).json({
            success: true,
            data: {
                ...registerInfo
            }
        })
    }
    const token = req.headers["token"]
    try {
        const decoded = jwt.verify(token, "2302B")
        console.log('解密token得到对象:', decoded)
    } catch (e) {
        return res.status(200).json({
            success: false,
            msg: "token已失效"
        })
    }
    next()
}
